import yaml
from django.db import models

from project.models import Project


# Create your models here.
class Endpoint(models.Model):
    """接口信息"""

    objects: models.QuerySet

    name = models.CharField("接口名称", max_length=32)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    method = models.CharField("请求方法", max_length=8)
    url = models.CharField("请求URL", max_length=255)
    params = models.JSONField(
        "查询字符串", max_length=10240, blank=True, null=True
    )  # 必须是json
    json = models.JSONField("json参数", max_length=10240, blank=True, null=True)
    data = models.JSONField("表单参数", max_length=10240, blank=True, null=True)
    headers = models.JSONField("请求头参数", max_length=10240, blank=True, null=True)
    cookies = models.JSONField("cookie参数", max_length=10240, blank=True, null=True)
    files = models.JSONField("文件上传参数", max_length=10240, blank=True, null=True)


class Case(models.Model):
    """接口用例"""

    objects: models.QuerySet

    name = models.CharField("用例名称", max_length=32)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    endpoint = models.ForeignKey(Endpoint, on_delete=models.CASCADE)

    # allure
    allure = models.JSONField("allure标注", max_length=10240, blank=True, null=True)
    # 用例步骤(实际传参)
    api_args = models.JSONField("接口用例参数", max_length=10240, blank=True, null=True)
    # 数据(变量)提取
    extract = models.JSONField("数据提取", max_length=10240, blank=True, null=True)
    # 断言
    validate = models.JSONField("断言", max_length=10240)

    # todo: 生成yaml文件保存到upload_yaml_cases这个路径下
    def save_yaml(self, path):
        # 构造用例执行需要的数据
        new_data = {}

        from .serializers import CaseSerializer

        serializer = CaseSerializer(self)
        json_data = serializer.data  # 得到json内容(字典格式)

        # 开始构造可以转成yaml文件的字典
        new_data["name"] = json_data["name"]
        new_data.update(json_data["allure"])

        # 更新接口需要传递的参数
        # 1.先处理id,name,project(因为这些不是接口用例执行需要的内容)
        json_data["endpoint_detail"].pop("id")
        json_data["endpoint_detail"].pop("name")
        json_data["endpoint_detail"].pop("project")
        # 2.将接口用例执行需要的内容加到request这个key中
        new_data["request"] = {}
        for k, v in json_data["endpoint_detail"].items():
            if not v:
                continue
            new_data["request"][k] = v
        # 添加请求参数
        for k, v in json_data["api_args"].items():
            new_data["request"][k] = v
        # 数据提取+断言
        new_data.update({"extract": json_data["extract"]})
        new_data.update({"validate": json_data["validate"]})

        # 生成yaml用例文件
        with open(
            path / f"test_{self.id}_{self.name}.yaml", "w", encoding="utf-8"
        ) as f:
            yaml.safe_dump(new_data, f, allow_unicode=True)
